<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量导入权限"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="batch-import-content">
      <!-- 导入说明 -->
      <el-alert
        title="导入说明"
        type="info"
        :closable="false"
        class="import-tip"
      >
        <template #default>
          <div class="tip-content">
            <p>1. 支持JSON格式的权限数据批量导入</p>
            <p>2. 权限类型：MENU（菜单）、BUTTON（按钮）、API（接口）</p>
            <p>3. 必填字段：name（权限名称）、code（权限代码）、type（权限类型）</p>
            <p>4. 可选字段：parentId（父级ID）、path（路径）、icon（图标）等</p>
          </div>
        </template>
      </el-alert>

      <!-- 导入方式选择 -->
      <el-card class="import-method-card">
        <template #header>
          <span>选择导入方式</span>
        </template>
        
        <el-radio-group v-model="importMethod" class="import-method-group">
          <el-radio-button label="json">JSON数据</el-radio-button>
          <el-radio-button label="file">文件上传</el-radio-button>
          <el-radio-button label="template">使用模板</el-radio-button>
        </el-radio-group>
      </el-card>

      <!-- JSON数据输入 -->
      <el-card v-if="importMethod === 'json'" class="json-input-card">
        <template #header>
          <span>JSON数据输入</span>
        </template>
        
        <el-input
          v-model="jsonData"
          type="textarea"
          :rows="15"
          placeholder="请输入JSON格式的权限数据..."
          class="json-textarea"
        />
        
        <div class="json-actions">
          <el-button @click="validateJson">验证JSON</el-button>
          <el-button type="primary" @click="parseJson">解析数据</el-button>
        </div>
      </el-card>

      <!-- 文件上传 -->
      <el-card v-if="importMethod === 'file'" class="file-upload-card">
        <template #header>
          <span>文件上传</span>
        </template>
        
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :on-change="handleFileChange"
          :before-upload="beforeUpload"
          accept=".json"
          drag
          class="file-uploader"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传JSON文件，且不超过2MB
            </div>
          </template>
        </el-upload>
      </el-card>

      <!-- 模板选择 -->
      <el-card v-if="importMethod === 'template'" class="template-card">
        <template #header>
          <span>选择模板</span>
        </template>
        
        <div class="template-options">
          <el-button @click="useMenuTemplate">菜单权限模板</el-button>
          <el-button @click="useButtonTemplate">按钮权限模板</el-button>
          <el-button @click="useApiTemplate">API权限模板</el-button>
          <el-button @click="useFullTemplate">完整权限模板</el-button>
        </div>
      </el-card>

      <!-- 数据预览 -->
      <el-card v-if="parsedData.length > 0" class="preview-card">
        <template #header>
          <span>数据预览</span>
        </template>
        
        <el-table
          :data="parsedData"
          style="width: 100%"
          border
          max-height="300"
        >
          <el-table-column prop="name" label="权限名称" min-width="120" />
          <el-table-column prop="code" label="权限代码" min-width="120" />
          <el-table-column prop="type" label="类型" width="80">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.type)" size="small">
                {{ getTypeLabel(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="path" label="路径" min-width="150" show-overflow-tooltip />
          <el-table-column prop="parentId" label="父级ID" width="80" />
          <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
          <el-table-column label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.valid ? 'success' : 'danger'" size="small">
                {{ row.valid ? '有效' : '无效' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="preview-summary">
          <el-tag type="success">有效数据：{{ validDataCount }}</el-tag>
          <el-tag type="danger">无效数据：{{ invalidDataCount }}</el-tag>
        </div>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleImport" 
          :loading="importing"
          :disabled="validDataCount === 0"
        >
          导入权限
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElUpload } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { permissionApi, CreatePermissionDto, PERMISSION_TYPE_OPTIONS } from '../api/permission'

// Props
interface Props {
  modelValue: boolean
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

// 上传组件引用
const uploadRef = ref<InstanceType<typeof ElUpload> | null>(null)

// 导入状态
const importing = ref(false)

// 导入方式
const importMethod = ref('json')

// JSON数据
const jsonData = ref('')

// 解析后的数据
const parsedData = ref<any[]>([])

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 计算属性
const validDataCount = computed(() => {
  return parsedData.value.filter(item => item.valid).length
})

const invalidDataCount = computed(() => {
  return parsedData.value.filter(item => !item.valid).length
})

// 验证JSON
const validateJson = () => {
  try {
    JSON.parse(jsonData.value)
    ElMessage.success('JSON格式正确')
  } catch (error) {
    ElMessage.error('JSON格式错误')
  }
}

// 解析JSON
const parseJson = () => {
  try {
    const data = JSON.parse(jsonData.value)
    if (!Array.isArray(data)) {
      ElMessage.error('JSON数据必须是数组格式')
      return
    }
    
    parsedData.value = data.map(item => ({
      ...item,
      valid: validatePermissionData(item)
    }))
    
    ElMessage.success(`解析完成，共 ${data.length} 条数据`)
  } catch (error) {
    ElMessage.error('JSON解析失败')
  }
}

// 验证权限数据
const validatePermissionData = (data: any): boolean => {
  const requiredFields = ['name', 'code', 'type']
  return requiredFields.every(field => data[field])
}

// 文件变化处理
const handleFileChange = (file: any) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    jsonData.value = e.target?.result as string
    parseJson()
  }
  reader.readAsText(file.raw)
}

// 上传前验证
const beforeUpload = (file: File) => {
  const isJson = file.type === 'application/json' || file.name.endsWith('.json')
  if (!isJson) {
    ElMessage.error('只能上传JSON文件')
    return false
  }
  
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('文件大小不能超过2MB')
    return false
  }
  
  return true
}

// 使用菜单模板
const useMenuTemplate = () => {
  jsonData.value = JSON.stringify([
    {
      name: '系统管理',
      code: 'SYSTEM_MANAGEMENT',
      type: 'MENU',
      path: '/system',
      icon: 'Setting',
      order: 1,
      show: true,
      enable: true,
      description: '系统管理菜单'
    },
    {
      name: '用户管理',
      code: 'USER_MANAGEMENT',
      type: 'MENU',
      path: '/system/user',
      icon: 'User',
      parentId: 1,
      order: 1,
      show: true,
      enable: true,
      description: '用户管理菜单'
    }
  ], null, 2)
  parseJson()
}

// 使用按钮模板
const useButtonTemplate = () => {
  jsonData.value = JSON.stringify([
    {
      name: '新增用户',
      code: 'USER_CREATE',
      type: 'BUTTON',
      method: 'POST',
      parentId: 1,
      order: 1,
      enable: true,
      description: '新增用户按钮'
    },
    {
      name: '编辑用户',
      code: 'USER_EDIT',
      type: 'BUTTON',
      method: 'PATCH',
      parentId: 1,
      order: 2,
      enable: true,
      description: '编辑用户按钮'
    }
  ], null, 2)
  parseJson()
}

// 使用API模板
const useApiTemplate = () => {
  jsonData.value = JSON.stringify([
    {
      name: '获取用户列表',
      code: 'USER_LIST_API',
      type: 'API',
      path: '/api/users',
      method: 'GET',
      order: 1,
      enable: true,
      description: '获取用户列表API'
    },
    {
      name: '创建用户',
      code: 'USER_CREATE_API',
      type: 'API',
      path: '/api/users',
      method: 'POST',
      order: 2,
      enable: true,
      description: '创建用户API'
    }
  ], null, 2)
  parseJson()
}

// 使用完整模板
const useFullTemplate = () => {
  jsonData.value = JSON.stringify([
    {
      name: '系统管理',
      code: 'SYSTEM_MANAGEMENT',
      type: 'MENU',
      path: '/system',
      icon: 'Setting',
      order: 1,
      show: true,
      enable: true,
      description: '系统管理菜单'
    },
    {
      name: '用户管理',
      code: 'USER_MANAGEMENT',
      type: 'MENU',
      path: '/system/user',
      icon: 'User',
      parentId: 1,
      order: 1,
      show: true,
      enable: true,
      description: '用户管理菜单'
    },
    {
      name: '新增用户',
      code: 'USER_CREATE',
      type: 'BUTTON',
      method: 'POST',
      parentId: 2,
      order: 1,
      enable: true,
      description: '新增用户按钮'
    },
    {
      name: '获取用户列表',
      code: 'USER_LIST_API',
      type: 'API',
      path: '/api/users',
      method: 'GET',
      order: 1,
      enable: true,
      description: '获取用户列表API'
    }
  ], null, 2)
  parseJson()
}

// 导入权限
const handleImport = async () => {
  if (validDataCount.value === 0) {
    ElMessage.warning('没有有效的权限数据')
    return
  }
  
  importing.value = true
  try {
    const validData = parsedData.value.filter(item => item.valid)
    const createData: CreatePermissionDto[] = validData.map(item => {
      const { valid, ...permissionData } = item
      return permissionData
    })
    
    const res = await permissionApi.batchCreatePermissions(createData)
    
    if (res && res.code === 200) {
      ElMessage.success(`成功导入 ${validData.length} 个权限`)
      emit('success')
    } else {
      ElMessage.error('导入失败')
    }
  } catch (error) {
    ElMessage.error('导入失败')
  } finally {
    importing.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  // 重置数据
  jsonData.value = ''
  parsedData.value = []
  importMethod.value = 'json'
}

// 获取类型标签类型
const getTypeTagType = (type: string): string => {
  const typeMap: Record<string, string> = {
    'MENU': 'primary',
    'BUTTON': 'success',
    'API': 'warning'
  }
  return typeMap[type] || 'info'
}

// 获取类型标签文本
const getTypeLabel = (type: string): string => {
  const option = PERMISSION_TYPE_OPTIONS.find(opt => opt.value === type)
  return option ? option.label : type
}
</script>

<style scoped>
.batch-import-content {
  padding: 0;
}

.import-tip {
  margin-bottom: 20px;
}

.tip-content p {
  margin: 4px 0;
  font-size: 14px;
}

.import-method-card {
  margin-bottom: 20px;
}

.import-method-group {
  width: 100%;
}

.json-input-card {
  margin-bottom: 20px;
}

.json-textarea {
  margin-bottom: 10px;
}

.json-actions {
  display: flex;
  gap: 8px;
}

.file-upload-card {
  margin-bottom: 20px;
}

.file-uploader {
  width: 100%;
}

.template-card {
  margin-bottom: 20px;
}

.template-options {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.preview-card {
  margin-bottom: 20px;
}

.preview-summary {
  margin-top: 10px;
  display: flex;
  gap: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
